package sf.ext.gen;

import sf.database.dbinfo.TableInfo;
import sf.database.mapper.annotation.OrmMapper;

import java.util.HashMap;
import java.util.Map;

import static sf.ext.gen.PojoGen.CR;

public class MapperCodeGen implements CodeGen {
    String pkg = null;
    private String mapperTemplate = "";
    /**
     * 只生成mapper,通过交由spring 代理
     */
    private boolean onlyMapper;

    public MapperCodeGen() {
        mapperTemplate = GenUtils.getTemplate("/template/gen/mapper.enjoy");
    }

    public MapperCodeGen(String pkg) {
        this();
        this.pkg = pkg;
    }

    public String getMapperTemplate() {
        return mapperTemplate;
    }

    public void setMapperTemplate(String mapperTemplate) {
        this.mapperTemplate = mapperTemplate;
    }

    public boolean isOnlyMapper() {
        return onlyMapper;
    }

    public void setOnlyMapper(boolean onlyMapper) {
        this.onlyMapper = onlyMapper;
    }

    @Override
    public void genCode(String srcPath, String entityPkg, String entityClass, TableInfo tableDesc, GenConfig config, boolean isDisplay) {
        if (pkg == null) {
            pkg = entityPkg;
        }
        if (srcPath == null) {
            srcPath = GenUtils.getJavaSRCPath();
        }
        Map<String, Object> map = new HashMap<>();
        String mapperClass = entityClass + "DAO";
        map.put("className", mapperClass);
        map.put("package", pkg);
        map.put("entityClass", entityClass);
        map.put("CR", CR);
        if (onlyMapper) {
            map.put("ormMapper", OrmMapper.class.getName());
        }

        String mapperHead = "import " + entityPkg + ".*;" + CR;
        map.put("imports", mapperHead);
        String mapperCode = GenUtils.renderByEnjoy(map, mapperTemplate);
        if (isDisplay) {
            System.out.println(mapperCode);
        } else {
            try {
                GenUtils.saveSourceFile(srcPath, pkg, mapperClass, mapperCode);
            } catch (Exception e) {
                throw new RuntimeException("mapper代码生成失败", e);
            }
        }

    }

}
